package com.story.web.controllers;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.story.domain.User;
import com.story.model.emums.LoginType;
import com.story.service.IUserService;
import com.story.web.shiro.token.StoryLoginToken;
import com.story.web.utils.WebUtils;

@Controller
public class IndexController extends BaseController {
	@Autowired
	private IUserService userService;
	
	private static final String USER_LOGIN_TYPE = LoginType.USER.toString();
	
	@RequestMapping("/")
	public String index(RedirectAttributes redirect,Model model){
		String username = (String) SecurityUtils.getSubject().getPrincipal();
		System.out.println("indexController----"+username);
		if(username==null){
			redirect.addFlashAttribute("error", "您还没有登陆，请登陆!");
			return "redirect:/login";
		}
		User user = userService.findoneByUsername(username);
		if(user == null){
			redirect.addFlashAttribute("error", "用户名或密码错误!");
			return "redirect:/login";
		}
		if(Boolean.FALSE.equals(user.getActiveStatus())){
			model.addAttribute("id", user.getUid());
			return "user/active";
		}
		return "index";
	}
	
	@RequestMapping(value="/registe/do",method=RequestMethod.POST)
	public String doRegiste(@Validated User user,BindingResult result,RedirectAttributes redirect,HttpServletRequest request) throws Exception{
		String msg = "";
		Map<String,String> map = new HashMap<String,String>();
		if(result.hasFieldErrors()){
			List<FieldError> errors = result.getFieldErrors();
			for(int i=0;i<errors.size();i++){
				map.put(errors.get(i).getField(), errors.get(i).getDefaultMessage());
			}
			redirect.addFlashAttribute("errors", map);
			return "redirect:/registe";
		}
		if(userService.checkUsernameExisted(user.getUsername())){
			redirect.addFlashAttribute("error", "用户已存在！");
			return "redirect:/registe";
		}
		User initUser = WebUtils.init(request,user);
		userService.registeUser(initUser);
		msg = "注册成功!";
		redirect.addFlashAttribute("success", msg);
		return "redirect:/login";		
	}
	@RequestMapping(value="/login/do",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> doLogin(@RequestParam("username") String username,String password,String verifyNumber,HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		String verifyError = (String) request.getAttribute("shiroLoginFailure");	
		if(verifyError!=null && verifyError.equals("jCaptcha.error")){
			map.put("status", "1");
			map.put("msg", "验证码错误!");
			return map;
		}		
		Subject subject = SecurityUtils.getSubject();
		if(!subject.isAuthenticated()){
			StoryLoginToken token = new StoryLoginToken(username, password, USER_LOGIN_TYPE);		
			try {
				subject.login(token);
				Session session = subject.getSession();
				if(session == null){
					session = subject.getSession(true);
				}
				session.setAttribute("loginType", USER_LOGIN_TYPE);
				map.put("status", 0);
				map.put("msg", "登陆成功，正在跳转中...");
			} catch (UnknownAccountException ue) {
				map.put("status", 1);
				map.put("msg", "未找到此用户！");
			} catch (IncorrectCredentialsException ice) {
				map.put("status", 1);
				map.put("msg", "用户名或密码错误!");
			} catch (LockedAccountException lae) {
				map.put("status", 1);
				map.put("msg", "账号已冻结，请联系管理员!");
			} catch (AuthenticationException e) {
				map.put("status", 1);
				map.put("msg", "登陆出现错误...");
				e.printStackTrace();
			}
		}		
		return map;
	}
}
